import * as Fs from "fs";
import * as Path from "path";
import { DirTree } from "./dirTree";

export default class FileUtils {

    /** 根据后缀判断文件是否符合类型 */
    public static confirmEnding(str: string, target: string) {
        // 请把你的代码写在这里
        var start = str.length - target.length;
        var arr = str.substr(start, target.length);
        if (arr == target) {
            return true;
        }
        return false;
    }

    /**
     * 遍历文件夹获取所有文件
     * @param {string} rootPath 根目录
     * @param {string} endWith 文件后缀
     * @param {string[]} files 输出
     */
    public static resoveDirFiles(rootPath: string, endWith: string, deep: boolean = true, files?: string[]) {
        files = files || [];
        let paths = Fs.readdirSync(rootPath, "utf8");
        for (let path of paths) {
            path = rootPath + '/' + path;
            let stat = Fs.statSync(path);
            if (stat.isDirectory()) {
                if (!deep) continue;
                this.resoveDirFiles(path, endWith, true, files);
            }
            else if (!endWith) {
                files.push(path);
            }
            else if (this.confirmEnding(path, endWith)) {
                files.push(path);
            }
        }
        return files;
    }

    public static copyFile(src: string, dist: string) {
        let stat = Fs.statSync(src)
        if (stat.isFile()) {// 判断是文件还是目录
            Fs.writeFileSync(dist, Fs.readFileSync(src));
            console.log(`cp ${src} ==> ${dist}`);
        } else if (stat.isDirectory()) {
            this.copyDir(src, dist)// 当是目录是，递归复制
        }
    }

    /** 拷贝子目录 */
    protected static __copyDir(src: string, dist: string, deep: boolean = true) {
        let paths = Fs.readdirSync(src)
        paths.forEach((p) => {
            let _src = src + '/' + p;
            let _dist = dist + '/' + p;
            this.copyFile(_src, _dist);
        })
    }

    /*
    * 复制目录、子目录，及其中的文件
    * @param src {String} 要复制的目录
    * @param dist {String} 复制到目标目录
    */
    public static copyDir(src: string, dist: string) {
        var b = Fs.existsSync(dist)
        console.log("dist = " + dist)
        if (!b) {
            console.log("mk dist = ", dist)
            Fs.mkdirSync(dist);//创建目录
        }
        console.log("_copy start")
        this.__copyDir(src, dist);
    }

    //递归创建目录 同步方法  
    public static mkdirSync(dirname: string) {
        if (Fs.existsSync(dirname)) {
            return true;
        } else {
            if (this.mkdirSync(Path.dirname(dirname))) {
                console.log("mkdirsSync = " + dirname);
                Fs.mkdirSync(dirname);
                return true;
            }
        }
    }

    /** 将列表转成树状结构 */
    public static convertListToTree(paths: string[], root: string = "root"): DirTree {
        let dirTree = new DirTree(root);
        for (let i = 0; i < paths.length; i++) {
            dirTree.addFile(paths[i]);
        }
        return dirTree;
    }
}